package com.example.security;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.*;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    private static final Logger logger = LoggerFactory.getLogger(CustomAuthenticationProvider.class);
    
    @Autowired
    private UserDetailsService userDetailsService;
    
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String username = authentication.getName();
        String password = authentication.getCredentials().toString();
        logger.info("尝试认证用户: {}", username);

        try {
            // 1. 加载用户
            UserDetails userDetails = userDetailsService.loadUserByUsername(username);
            logger.info("找到用户: {}, 状态: enabled={}, accountNonLocked={}, accountNonExpired={}, credentialsNonExpired={}", 
                username, userDetails.isEnabled(), userDetails.isAccountNonLocked(), 
                userDetails.isAccountNonExpired(), userDetails.isCredentialsNonExpired());

            // 2. 验证密码
            boolean passwordMatches = passwordEncoder.matches(password, userDetails.getPassword());
            logger.info("密码验证结果: {}", passwordMatches);
            if (!passwordMatches) {
                logger.warn("密码错误: {}", username);
                throw new BadCredentialsException("密码错误");
            }

            // 3. 检查用户状态
            if (!userDetails.isEnabled()) {
                logger.warn("用户已被禁用: {}", username);
                throw new BadCredentialsException("账户已被禁用");
            }
            if (!userDetails.isAccountNonLocked()) {
                logger.warn("用户已被锁定: {}", username);
                throw new BadCredentialsException("账户已被锁定");
            }
            if (!userDetails.isAccountNonExpired()) {
                logger.warn("用户账号已过期: {}", username);
                throw new BadCredentialsException("账户已过期");
            }
            if (!userDetails.isCredentialsNonExpired()) {
                logger.warn("用户密码已过期: {}", username);
                throw new BadCredentialsException("凭证已过期");
            }

            logger.info("用户认证成功: {}", username);
            // 4. 创建认证成功的token
            return new UsernamePasswordAuthenticationToken(
                userDetails,
                password,
                userDetails.getAuthorities()
            );
        } catch (UsernameNotFoundException e) {
            logger.warn("用户不存在: {}", username);
            throw new BadCredentialsException("用户不存在");
        }
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
    }
} 